package hibernate.xml22;

import java.util.HashSet;
import java.util.Set;

import javassist.bytecode.Descriptor.Iterator;
import junit.framework.TestCase;

import org.hibernate.Session;
import org.hibernate.Transaction;

public class LazyForCollectionTest2 extends TestCase {

	/**
	 * 设置lazy=false
	 */
	public void testLoad1() {
		Session session = null;
		Transaction tx = null;
		try {
			session = HibernateUtil.getSession();
			tx = session.beginTransaction();
			//会发出sql
			Classes classes=(Classes)session.load(Classes.class, 1);
			//不会发出sql
			System.out.println("classes.name="+classes.getName());
			//不会发出sql
			Set students=classes.getStudents();
			//会发出sql
			for(java.util.Iterator iter=students.iterator();iter.hasNext();){
				Student student=(Student)iter.next();
				System.out.println("student.name="+student.getName());
			}
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
			tx.rollback();
		} finally {
			HibernateUtil.closeSession(session);
		}
	}
	/**
	 * 设置lazy=false
	 */
	public void testLoad2() {
		Session session = null;
		Transaction tx = null;
		try {
			session = HibernateUtil.getSession();
			tx = session.beginTransaction();
			//不会发出sql
			Classes classes=(Classes)session.load(Classes.class, 1);
			//会发出sql
			System.out.println("classes.name="+classes.getName());
			//不会发出sql
			Set students=classes.getStudents();
			//会发出sql,发出查询全部数据的sql
			System.out.println("student.count="+students.size());
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
			tx.rollback();
		} finally {
			HibernateUtil.closeSession(session);
		}
	}
}
